import 'package:bloc/bloc.dart';
import 'package:qgchat/http/models/HotIdsModel.dart';

import '../../../../http/apis/common.dart';
import '../../../../http/models/recommendModel.dart';

enum HotEvent { refresh, load }

class HotBloc extends Bloc<HotEvent, List<RecommendModel>> {
  int _page = 0;
  final int _limit = 6;

  List<RecommendModel> list = [];

  List<HotIdsModel> ids = [];

  HotBloc() {
    add(HotEvent.refresh);
  }

  @override
  Stream<List<RecommendModel>> mapEventToState(HotEvent event) async* {
    if (event == HotEvent.refresh) {
      _page = 0;
      ids = await CommonApis.recommendIds();
      list = await CommonApis.recommendPage(pageIds);
      yield List<RecommendModel>.from(anchorList);
      if (pageIds.length > 0) _page += _limit;
    }
    if (event == HotEvent.load) {
      final result = await CommonApis.recommendPage(pageIds);
      list.addAll(result);
      yield List<RecommendModel>.from(anchorList);
      if (pageIds.length > 0) _page += _limit;
    }
  }

  // 推荐主播的id列表
  List<int> get pageIds {
    if (_page > ids.length - 1) return [];
    if (_page + _limit > ids.length - 1 && _page < ids.length - 1) {
      return ids.sublist(_page, ids.length).map((e) => e.id).toList();
    }
    return ids.sublist(_page, _page + _limit).map((e) => e.id).toList();
  }

  // 推荐主播列表
  List<RecommendModel> get anchorList {
    final arr = ids.where((item) {
      for (var anchor in list) {
        if (anchor.memberToken == item.memberToken) {
          return true;
        }
      }
      return false;
    }).map<RecommendModel>((item) {
      RecommendModel info;
      for (var anchor in list) {
        if (anchor.memberToken == item.memberToken) {
          anchor.online = item.online;
          info = anchor;
        }
      }
      return info;
    }).toList();
    return arr;
  }

  @override
  List<RecommendModel> get initialState => [];
}
